<template>

  <div>
    <el-breadcrumb separator="/" style="color: black;font-weight: 700">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>账号管理</el-breadcrumb-item>
    </el-breadcrumb>
    <h1>账号管理</h1>
    <!--搜索表单-->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-button type="primary" @click="openAddDialog" style="display: none">添加</el-button>
      </el-col>

      <el-col :span="6">
        <el-form-item label="姓名">
          <el-input placeholder="姓名关键字" v-model="searchCriteria.USERNAME" clearable/>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item>
          <el-button type="primary" @click="searchOnSubmit">{{ buttonLabel }}</el-button>
          <el-button @click="searchOnReset">取消</el-button>
        </el-form-item>
      </el-col>
    </el-row>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          v-for="(item, index) in tableHeader"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
      >
        <template #default="scope">
          <div
              v-show="item.editable || scope.row.editable"
              class="editable-row"
          >
            <!-- 对于'AUTHORITY'列，显示下拉选择框 -->
            <template v-if="item.prop === 'AUTHORITY'">
              <el-select
                  v-model="scope.row[item.prop]"
                  :placeholder="`请选择${item.label}`"
                  size="small"
                  @change="handleSelectChange(scope.row, scope.$index, item.prop)"
              >
                <el-option
                    v-for="option in authorityOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
            </template>

            <!-- 对于其他输入类型的列，显示输入框 -->
            <template v-else-if="item.type === 'input'">
              <el-input
                  v-bind="{ readonly: ['ID'].includes(item.prop) && scope.row.editable }"
                  size="small"
                  v-model="scope.row[item.prop]"
                  :placeholder="`请输入${item.label}`"
                  @change="handleEdit(scope.$index, scope.row)"
              />
            </template>

              <template v-else-if="item.type === 'select'">
                  <!-- 新增：对于类型为'select'的列 -->
                  <el-select
                          v-model="scope.row[item.prop]"
                          :value="scope.row[item.prop]"
                          size="small"
                          @change="handleEdit(scope.$index, scope.row)"
                  >
                      <el-option
                              v-for="option in item.options"
                              :key="option.value"
                              :label="option.label"
                              :value="option.value"
                      />
                  </el-select>
              </template>


            <!-- 默认情况，即非编辑状态下显示文本 -->
            <template v-else>
              <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
            </template>

          </div>

          <!-- 非编辑状态下显示文本 -->
          <div
              v-show="!item.editable && !scope.row.editable"
              class="editable-row"
          >
            <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              v-show="!scope.row.editable"
              size="small"
              @click="scope.row.editable = true"
          >编辑信息
          </el-button
          >
          <el-button
              v-show="scope.row.editable"
              size="small"
              type="success"
              @click="saveEditedRow(scope.row)"
          >确定
          </el-button
          >
<!--          <el-button-->
<!--              v-show="!scope.row.editable"-->
<!--              size="small"-->
<!--              type="danger"-->
<!--              @click="DeleteUserData(scope.row.ID)"-->
<!--          >删除-->
<!--          </el-button-->
<!--          >-->
            <el-button
                    v-show="scope.row.editable"
                    size="small"
                    type="warning"
                    @click="cancelEdit(scope.row)"
            >取消</el-button
            >
        </template>
      </el-table-column>
    </el-table>



    <!-- 分页组件示例 -->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="totalElements"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
        style="margin-top: 20px;"
        v-if="showPagination"
    />
  </div>
</template>

<script setup>
import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {ref, reactive, onMounted, onUpdated, computed, nextTick} from 'vue';
import {get} from "@vueuse/core";
// 初始化数据
const item = reactive({
  ID: "",
  USERNAME: "",
  EMAIL:"",
  AUTHORITY: "",
  VALID: "",
    displayStatus:"",
});

const header = {
  prop: "key",
  label: "自定义",
  editable: false,
  type: "input",
};

const tableHeader = ref([
  // {
  //   prop: "ID",
  //   label: "ID",
  //   editable: false,
  //   type: "input",
  // },
  {
    prop: "USERNAME",
    label: "用户名",
    editable: false,
    type: "input"
  },
  {
    prop: "EMAIL",
    label: "邮箱",
    editable: false,
    type: "input"
  },
    {
    prop: "AUTHORITY",
    label: "角色",
    editable: false,
    type: "input"
  },
    {
        prop: "displayStatus",
        label: "状态",
        editable: false,
        type: "select", // 将类型更改为'select'
        options: [
            { label: "启用", value: 1 },
            { label: "禁用", value: 0 },
        ],
    },
]);


//分页相关状态
const currentPage = ref(1); // 当前页码，默认为第一页
const pageSize = ref(5); // 每页显示数量，默认为5条
const totalElements = ref(0);

// 初始化时加载第一页数据
onMounted(() => {
  fetchUserData();
  showPagination.value = true;
});
onUpdated(() => {
});

// 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
function handlePageChange(page) {
  currentPage.value = page;
  fetchUserData(page);
}

//tableData是一个空数组，用于存储表格的数据
const tableData = ref([]);

//模糊查询
const searchCriteria = reactive({
  USERNAME: "", // 用户姓名
});

const showPagination = ref(true);

const buttonLabel = computed(() => {
  showPagination.value = searchCriteria.USERNAME.trim() !== '' ;
  return searchCriteria.USERNAME.trim() === ''
      ? '查询所有'
      : '条件查询';
});

// 更新fetchUserData函数以支持分页查询
async function fetchUserData(current = currentPage.value, size = pageSize.value) {
  try {
    const response = await axios.get('/userInfo/page', {
      params: {
        currentPage: current,
        pageSize: size
      }
    });
    if (!response.data.errorCode || response.data.errorCode === "200") {
      // 更新tableData时，考虑分页数据结构
      //将接口返回的数据通过map方法遍历并转换为新的对象数组
      tableData.value = response.data.data.map(user =>
          ({
        ID: user.id,
        USERNAME: user.username,
        EMAIL: user.email,
            // 添加逻辑来转换AUTHORITY的值
        AUTHORITY: user.authority === 'ROLE_common' ? '普通管理员' : user.authority === 'ROLE_vip' ? '超级管理员' : user.authority,
              VALID: user.valid,
              // 添加新属性用于展示，根据VALID值决定
              displayStatus: user.valid === 1 ? '启用' : '禁用',
        editable: false,
      }));
      totalElements.value = response.data.total;
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
      console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
    }
  } catch (error) {
    ElMessage.error('获取数据过程中发生错误');
    console.error('Error fetching data:', error);
  }
}



// 搜索条件
async function searchOnSubmit() {
  try {
    // 调整API路径以匹配用户查询
    const response = await axios.get('/select', {
      params: {
        username: searchCriteria.USERNAME,
      },
    });

    if (response.data.errorCode === "200") {
      //后端查询到的数据中每个用户对象的id、username、email和valid字段的值
      // 映射到tableData中
      tableData.value = response.data.data.map(user => ({
        ID: user.id,
        USERNAME: user.username,
        EMAIL: user.email,
        AUTHORITY: user.authority,
          VALID: user.valid,
          // 添加新属性用于展示，根据VALID值决定
          displayStatus: user.valid === 1 ? '启用' : '禁用',
        editable: false,
      }));
      //    查询成功后把查询的结果添加到表单展示
      showPagination.value = false;
    } else {
      ElMessage.error('查询失败，请检查输入或重试');
      console.error('查询失败:', response.data.message || '未提供错误信息');
    }
  } catch (error) {
    ElMessage.error('查询过程中发生错误');
    console.error('查询错误:', error);
  }
}

//取消查询
const searchOnReset = async () => {
  showPagination.value = true;
  searchCriteria.USERNAME = "";
  await fetchUserData();
  showPagination.value = true;
};

//切换表格行进入编辑模式
function handleEdit(index,row) {
  row.editable = true;
}


// 定义handleSelectChange方法
const handleSelectChange = (row, index, prop) => {
  console.log('Selected value:', row[prop], 'at index', index);
  // 处理选择变化的逻辑
};

const authorityOptions = ref([
  { label: '普通管理员', value: 1 },
  { label: '超级管理员', value: 2 },
  // 其他选项...
]);


// 异步方法获取原始authorityId
async function getOriginalAuthorityId(ID) {
  console.log('getOriginalAuthorityId called with userId:', ID);
  try {
    const response = await axios.get(`/selectAuthority/${ID}`);
    console.log('getOriginalAuthorityId response:', response.data);
    return response.data; // 假设返回的是integer类型的authorityId
  } catch (error) {
    console.error('获取原始权限ID失败', error);
    return null;
  }
}
// 编辑
async function saveEditedRow(item) {
    if (item.displayStatus === '启用'  || item.displayStatus ==='禁用') {
        ElMessage.warning('请再次确认选择一次您的状态');
        return; // 停止执行保存逻辑
    }

  //校验用户名
  if (!/^[a-zA-Z0-9_-]{3,16}$/.test(item.USERNAME)) {
    ElMessage.warning('用户名只能包含字母、数字、下划线或横杠，长度在3到16个字符之间');
    return;
  }
  //校验邮箱
  if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(item.EMAIL)) {
    ElMessage.warning('邮箱格式不正确');
    return;
  }
  const selectedAuthority = authorityOptions.value.find(
      option => option.value === parseInt(item.AUTHORITY, 10)
  );

  if (!selectedAuthority) {
    ElMessage.warning('请先选择一次您的角色权限！');
    return;
  }
  const authorityId = selectedAuthority.value;
  try {
    const updatedUser = {
      id: item.ID,
      username: item.USERNAME,
      email: item.EMAIL,
      authority: item.AUTHORITY,
      // 如果authority_id字段实际上应该是authority的ID而不是整个选项对象，使用以下行代替
      authority_id: authorityId,
      valid: item.displayStatus,
    };
    const response = await axios.put(`/updateInfo`, updatedUser);

    if (response.data.errorCode === "200") {
      ElMessage.success('更新成功');
      item.editable = false;
      await fetchUserData();
    } else {
      ElMessage.error(response.data.msg || '更新失败，请重试');
    }
  } catch (error) {
    console.error('更新过程中发生错误', error);
    ElMessage.error('更新失败，请稍后重试');
  }
}
//取消修改按钮
const cancelEdit = (row) => {
    row.editable = false;
    //    恢复原来数据
    Object.assign(row, {
        USERNAME: row.USERNAME,
        EMAIL: row.EMAIL,
        AUTHORITY: row.AUTHORITY,
        VALID: row.VALID,
    });
    ElMessage.warning('已取消修改');
    fetchUserData();
};

//删除
async function DeleteUserData(ID) {
  // 使用ElMessageBox显示确认对话框
  const confirmResult = await ElMessageBox.confirm(
      '确定要删除此用户信息吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  );
  // 如果用户点击了确认按钮（confirm）
  if (confirmResult === 'confirm') {
    try {
      const response = await axios.delete(`/delete/${ID}`);

      if (!response.data.errorCode || response.data.errorCode === "200") {
        ElMessage.success('删除成功');
        await fetchUserData(); // 刷新表格数据
      } else {
        ElMessage.error('删除失败，请重试');
      }
    } catch (error) {
      console.error('Error deleting data:', error);
      ElMessage.error('删除失败');
    }
  }
  // 如果用户点击取消，则什么都不做，对话框自动关闭
}
</script>

<style scoped>

</style>